package com.mdnote.practice.binary_tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/9/30 0030
 * @description
 */
public class LeetCode107 {

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<List<Integer>> resList = new ArrayList<>();
        _levelOrderBotton(root, resList);
        return resList;
    }

    public void _levelOrderBotton(TreeNode node, List<List<Integer>> resList) {
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(node);
        while(!queue.isEmpty()) {
            int size = queue.size();

            List<Integer> list = new ArrayList<Integer>();
            for (int i = 0; i < size; i++) {
                // get node
                TreeNode temp = queue.removeFirst();
                // process
                list.add(temp.val);
                // next node
                if (temp.left != null) {
                    queue.addLast(temp.left);
                }
                if (temp.right != null) {
                    queue.addLast(temp.right);
                }

            }
            resList.add(0, list);
        }
    }
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
}
